<template>
  <div class="woReviewPage">
    <div class="workTimeBox">
      <div class="row infoBox justify-between items-center">
        <span class="col-12 col-sm-auto infoSpan">工单编号: {{ orderNo }}</span>
        <span class="col-12 col-sm-auto infoSpan">工序 : {{ flow }}</span>
        <span
          v-if="startedReview && currentStatus === 'start'"
          class="col-12 col-sm-auto infoSpan"
          >工序状态 : {{ roleName }}审核中</span
        >
        <span
          v-else-if="startedReview && currentStatus === 'complete'"
          class="col-12 col-sm-auto infoSpan"
          >工序状态 : {{ roleName }}审核完成</span
        >
        <span v-else class="col-12 col-sm-2 infoSpan"
          ><q-btn
            label="开始"
            color="indigo-3"
            class="startBtn"
            @click="startReview()"
            :disable="userStore.currentDept.source !== wodetailsStore.orderInfo.source_code || !editable"
        /></span>
      </div>
    </div>

    <div v-show="startedReview" class="row reviewBox">
      <div class="col-12 col-sm-6 reviewResult">
        <div class="row items-center">
          <div class="col">
            <q-btn-toggle
              v-model="result"
              spread
              no-caps
              toggle-color="deep-purple-8"
              color="white"
              text-color="black"
              :options="[
                { label: '不合格', value: 'fail' },
                { label: '合格', value: 'pass' },
              ]"
              :disable="!editable"
              class="resultBtn"
            />
          </div>
        </div>
        <div class="row remarkBox">
          <div class="col">
            <q-input
              v-model="remark"
              clearable
              clear-icon="close"
              filled
              autogrow
              bg-color="white"
              color="black"
              placeholder="备注 (选择填): "
              :disable="!editable"
            />
          </div>
        </div>
        <div v-if="result === 'fail'" class="row frResultBox">
          <div class="col">
            <div class="row items-center justify-between">
              <span class="col-auto">已选择不合格原因及数量:</span>
              <div
                v-show="mobileVer && editable"
                class="col-auto addRemoveBtn"
                @click="editable ? (frDialog = true) : (frDialog = false)"
              >
                <q-icon name="fa-solid fa-plus" class="addRemoveSVG" />
              </div>
            </div>
            <div
              v-for="fr in selectedFR.filter((fr) => fr.isChosen)"
              :key="fr.id"
              class="row text-center items-center frChosenBox"
            >
              <div class="col fr-chosen">{{ fr.reason }}</div>
              <div class="col-3 row fr-qty items-center">
                <div class="col fr-qty-input">
                  <q-input
                    v-model="fr.qty"
                    type="number"
                    :min="1"
                    bg-color="white"
                    filled
                    dense
                    :disable="!editable"
                  />
                </div>
                <div class="col-auto fr-unit">{{ fr.unit }}</div>
              </div>
            </div>
          </div>
        </div>
        <div class="row submitBtnBox" v-if="editable">
          <q-btn
            class="col"
            label="提交"
            color="deep-purple-10"
            @click="submit()"
          />
        </div>
      </div>

      <!-- Tablet & Desktop: Fail Reason Choices -->
      <div
        v-show="result === 'fail' && !mobileVer && editable"
        class="col-12 col-sm-6 failReason"
      >
        <div class="row items-center">
          <span class="frTitle">新增不合格原因</span>
          <span class="reqFieldMsg">(必须填写)</span>
        </div>

        <div
          v-for="fr in selectedFR"
          :key="fr.id"
          class="row items-center justify-center frItem"
        >
          <div
            class="col frChoice text-center"
            :class="{ addFrChoice: fr.isChosen }"
          >
            {{ fr.reason }}
          </div>
          <div class="col-auto addRemoveBtn" @click="toggleFailReason(fr.id)">
            <q-icon
              v-if="!fr.isChosen"
              name="fa-solid fa-plus"
              class="addRemoveSVG"
            />
            <q-icon
              v-if="fr.isChosen"
              name="fa-solid fa-minus"
              class="addRemoveSVG"
            />
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- Choose Fail Reasons Dialog -->
  <q-dialog v-model="frDialog" class="frDialogBox">
    <q-card style="width: 700px; max-width: 80vw" class="">
      <q-card-section
        class="bg-deep-purple-9 text-white row items-center justify-center"
      >
        <div class="row items-center">
          <span class="text-h6 f-bold">新增不合格原因</span>
          <span class="reqFieldMsg">(必须填写)</span>
        </div>
      </q-card-section>
      <q-card-section class="bg-deep-purple-1 frItemBox">
        <div
          v-for="fr in selectedFR"
          :key="fr.id"
          class="row items-center justify-center frItem"
        >
          <div
            class="col frChoice text-center self-center"
            :class="{ addFrChoice: fr.isChosen }"
          >
            <span>{{ fr.reason }}</span>
          </div>
          <div class="col-auto addRemoveBtn" @click="toggleFailReason(fr.id)">
            <q-icon
              v-if="!fr.isChosen"
              name="fa-solid fa-plus"
              class="addRemoveSVG"
            />
            <q-icon
              v-if="fr.isChosen"
              name="fa-solid fa-minus"
              class="addRemoveSVG"
            />
          </div>
        </div>
      </q-card-section>

      <q-card-actions align="center">
        <q-btn
          color="deep-purple-4"
          class="confirmBtn"
          label="确定"
          v-close-popup
        />
      </q-card-actions>
    </q-card>
  </q-dialog>

  <!-- Confirm Reset Dialog -->
  <q-dialog v-model="confirmReset">
    <q-card>
      <q-card-section
        class="bg-deep-purple-9 text-white row items-center justify-center"
      >
        <div class="text-h6 f-bold">重设审核结果</div>
      </q-card-section>
      <q-card-section class="row items-center">
        <span>审核结果和时间将会删除，确定重设审核结果?</span>
      </q-card-section>

      <q-card-actions align="center">
        <q-btn label="取消" color="grey-6" v-close-popup />
        <q-btn
          label="确定"
          color="deep-purple-6"
          v-close-popup
          @click="submit()"
        />
      </q-card-actions>
    </q-card>
  </q-dialog>
</template>

<script setup>
import { ref, toRaw } from "vue";
import { useQuasar } from "quasar";
import { useUserStore } from "src/stores/modules/userStore";
import { useWOReviewStore } from "src/stores/modules/woReviewStore";
import { useWoDetailsStore } from "src/stores/modules/wodetailsStore";

const $q = useQuasar();
const userStore = useUserStore();
const woReviewStore = useWOReviewStore();
const wodetailsStore = useWoDetailsStore();
let role = null;
let roleName = null;
let accID = null;
const currentStatus = ref(null);
const orderNo = ref("");
const flow = ref("");
const result = ref("pass");
const remark = ref("");
const failReason = ref("");
const checkTime = ref("");
const startedReview = ref(false); // testing: Should be "null" in normal case
const editable = ref(false);

const selectedFR = ref([]);

const confirmReset = ref(false);

// Function: Initialization
const initWOReview = () => {
  role = userStore.currentDept ? userStore.currentDept.roleGroup : null;
  roleName = userStore.currentDept
    ? userStore.currentDept.role_chinese_name
    : null;
  accID = userStore.currentDept.accID ? userStore.currentDept.accID : null;

  // Check If allow to do any actions for this wo
  currentStatus.value = woReviewStore.currentStatus;
  console.log(woReviewStore.editable);
  console.log(woReviewStore.currentStatus);
  console.log(woReviewStore.allow_reset);
  startedReview.value =
    woReviewStore.currentStatus === "start" ||
    woReviewStore.currentStatus === "complete";
  editable.value = woReviewStore.editable;
  orderNo.value = woReviewStore.orderNo;
  flow.value = woReviewStore.flow;
  remark.value = woReviewStore.remark;
  result.value =
    woReviewStore.result == ""
      ? "pass"
      : woReviewStore.result == null
      ? "pass"
      : woReviewStore.result;
  failReason.value = woReviewStore.failReason;
  checkTime.value = woReviewStore.checkTime;
};
initWOReview();

// Function: Start WO Review
const startReview = () => {
  // call api to start
  startedReview.value = true;
  woReviewStore.setCurrentStatus("start");
  currentStatus.value = "start";
  startedReview.value = true;
  woReviewStore.qcUpdateWOReview(
    accID,
    orderNo.value,
    null,
    null,
    null,
    "start"
  );
};

async function initWoDetail() {
  roleName = userStore.currentDept.role_chinese_name;
  accID = userStore.currentDept.accID;
  await wodetailsStore.getWODetails(orderNo.value, accID, roleName);
}

// Function: load Fail Reasons
const loadFailReason = async () => {
  await initWoDetail();
  const loadFR = woReviewStore.getQCFailReason;
  console.log(loadFR);
  selectedFR.value = [];
  selectedFR.value = toRaw(loadFR);
};
loadFailReason();

// Function: Toggle Fail Reasons
const toggleFailReason = (id) => {
  const fr = selectedFR.value.find((e) => e.id === id);
  fr.isChosen = !fr.isChosen;
};

// Function: Submit wo Review
const submit = async () => {
  if (woReviewStore.currentStatus === "complete" && !confirmReset.value) {
    // pop alert box
    confirmReset.value = true;
  } else {
    let failReason = toRaw(selectedFR.value);
    failReason = failReason.filter((e) => e.isChosen);
    console.log("failReason: ", failReason);
    let isFailed =
      result.value === "fail" ? true : result.value === "pass" ? false : null;
    console.log(isFailed);
    if (isFailed && failReason.length == 0) {
      console.log("failReason", failReason);
      $q.notify({
        type: "negative",
        textColor: "white",
        message: "请附上不合格原因 !",
        timeout: 2000,
        position: "center",
      });
      return;
    }
    if (isFailed && failReason.length > 0) {
      let check = 0;
      for (let r of failReason) {
        console.log(r);
        if (r.qty == 0) {
          check += 1;
        }
      }
      if (check > 0) {
        $q.notify({
          type: "negative",
          textColor: "white",
          message: '不合格件数不能 0 !',
          timeout: 2000,
          position: "center",
        });
        return;
      }
    }

    const res = await woReviewStore.qcUpdateWOReview(
      accID,
      orderNo.value,
      failReason,
      remark.value,
      isFailed,
      "complete"
    );
    if (res) {
      woReviewStore.setCurrentStatus("complete");
      woReviewStore.setReviewResult(result.value);
      currentStatus.value = "complete";
      // startedReview.value = true
      $q.notify({
        type: "positive",
        textColor: "white",
        message: "成功审核工单!",
        timeout: 2000,
        position: "center",
      });
      await initWoDetail();
      initWOReview();
      editable.value = false;
      woReviewStore.allow_reset = true;
      woReviewStore.editable = false;

      // initWOReview();
      // loadFailReason();
    } else {
      //alert
      $q.notify({
        type: "negative",
        textColor: "white",
        message: "错误发生 !",
        timeout: 2000,
        position: "center",
      });
    }
  }
};

console.log("editable", editable.value);
console.log("selectedFR", selectedFR.value);

// Function: Check window size -> Responsive
window.addEventListener("resize", checkScreenSize, false);
const mobileVer = ref(false);
const frDialog = ref(false);
function checkScreenSize() {
  if (window.innerWidth <= 600) {
    mobileVer.value = true;
  } else {
    mobileVer.value = false;
  }
}
checkScreenSize();
</script>

<style lang="scss" scoped>
.frDialogBox {
  .reqFieldMsg {
    color: #e02f23;
    margin-left: 5px;
    font-size: 0.8rem;
  }
  .frItemBox {
    max-height: 500px;
    overflow: auto;
  }

  .frItem {
    width: 100%;
    margin-top: 5px;
    height: 30px;
    .frChoice {
      background-color: white;
      height: 100% !important;
      padding-top: 3px;
      padding-bottom: 3px;
      @media (max-width: 650px) {
        font-size: 1rem;
      }
    }
    .addFrChoice {
      background-color: #cad9ff !important;
    }
    .addRemoveBtn {
      background-color: #5f51c0;
      .addRemoveSVG {
        color: white;
        padding-left: 3px;
        padding-right: 2px;
        @media (max-width: 650px) {
          font-size: 1rem;
        }
      }
    }
  }
}

.woReviewPage {
  margin-top: 10px;
  width: 99%;
  margin-left: auto;
  margin-right: auto;
  .workTimeBox {
    background-color: white;
    border-radius: 5px;
    padding: 10px 10px 10px 10px;
    width: 98%;
    margin-left: auto;
    margin-right: auto;
    .infoBox {
      // width: 95%;
      .startBtn {
        width: 100%;
      }
      .infoSpan {
        font-weight: bold;
        font-size: 1.2rem;
        @media (max-width: 480px) {
          font-size: 0.9rem !important;
        }
      }
    }
  }

  .reviewBox {
    margin-top: 10px;
    font-size: 1.2rem;
    width: 100%;
    @media (max-width: 650px) {
      font-size: 0.9rem !important;
    }
    @media (max-width: 800px) {
      font-size: 1rem !important;
    }
    .reviewResult {
      padding-left: 3px;
      padding-right: 3px;
      .resultBtn {
        width: 98%;
      }
      .remarkBox {
        margin-top: 10px;
        width: 98%;
      }
      .frResultBox {
        margin-top: 10px;
        width: 98%;
        background-color: rgba(255, 255, 255, 0.774);
        border-radius: 5px;
        padding: 10px 10px 10px 10px;
        .frTitle {
          color: #5f51c0;
          font-weight: bold;
          font-size: 1rem;
        }
        .addRemoveBtn {
          background-color: #5f51c0;
          padding: 3px 5px 3px 5px;
          text-align: center;
          height: 100%;
          .addRemoveSVG {
            color: white;
          }
        }
        .frChosenBox {
          margin-top: 5px;
          width: 100%;
          @media (max-width: 650px) {
            margin-top: 2px;
          }
          .fr-chosen {
            background-color: white;
            padding-top: 5px;
            padding-bottom: 5px;
          }
          .fr-qty {
            margin-left: 5px;
          }
          .fr-qty-input {
            margin-right: 3px;
          }
          .fr-unit {
            color: #5f51c0;
            font-weight: bold;
          }
        }
      }
      .submitBtnBox {
        margin-top: 10px;
        width: 98%;
      }
    }

    .failReason {
      background-color: rgba(255, 255, 255, 0.685);
      padding: 10px 10px 10px 10px;
      border-radius: 5px;
      @media (max-width: 650px) {
        font-size: 0.7rem !important;
      }
      .frTitle {
        color: #5f51c0;
        font-weight: bold;
      }
      .reqFieldMsg {
        color: #e02f23;
        margin-left: 5px;
        font-size: 0.8rem;
      }
      .frItem {
        width: 100%;
        margin-top: 5px;
        .frChoice {
          background-color: white;
          padding-top: 3px;
          padding-bottom: 3px;
        }
        .addFrChoice {
          background-color: #cad9ff !important;
        }
        .addRemoveBtn {
          background-color: #5f51c0;
          padding: 3px 5px 3px 5px;
          text-align: center;
          height: 100%;
          .addRemoveSVG {
            color: white;
          }
        }
      }
    }
  }
}
</style>
